import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:get/get.dart';
import 'package:kq_flutter_core_widget/widgets/button/kq_ink_well.dart';
import 'package:kq_flutter_widgets/theme/kq_theme_manager.dart';

import '../../../resources/kq_theme_colors.dart';
import '../../../resources/l10n/kq_intl.dart';
import '../../datePicker/kq_picker.dart';
import '../../divider/kq_divider.dart';
import '../kq_botton_sheet_manger.dart';

/// 通用数据多级联动选择底部弹窗
///
/// @author 高裕
///
class KqLinkagePickerBottomSheet extends StatefulWidget {
  /// 总层级
  final int totalLevel;

  /// 初始化选中
  final List<int>? initSelect;

  /// 左边按钮文字，默认“取消”
  final String? leftBtnText;

  /// 右边按钮文字，默认“确定”
  final String? rightBtnText;

  /// 点击【取消】回调给调用方的回调事件
  final Function()? onCancel;

  /// 滚动选择时候,填充层级数据，0级时，后三个数据不返回
  /// [fillLevel] 要填充的层级,从第0级开始
  /// [lastLevelData] 上个层级的数据
  /// [lastLevelSelectIndex] 上个层级的选中项
  /// [lastLevelSelectIndex] 上个层级的选中项
  /// 返回当前选中项列表
  final List<dynamic> Function(int fillLevel, List<dynamic>? lastLevelData,
      int? lastLevelSelectIndex, dynamic lastLevelSelectData) onFillData;

  /// 确认回调，return true 则代表关闭对话框，return false，则代表不关闭对话框
  final bool Function(List<int> selectIndex, List<dynamic> selectData)?
      onConfirm;

  /// 显示数据内的那个参数
  final String? Function(int level, dynamic item) showWhatInItem;

  /// 自定义头部
  final List<Widget>? customHeaders;

  final KqPickerTitleConfig pickerTitleConfig;

  /// 是否显示底部按钮
  final bool showBottomButton;

  final bool canPop;

  const KqLinkagePickerBottomSheet({
    Key? key,
    required this.totalLevel,
    required this.onFillData,
    required this.showWhatInItem,
    this.initSelect,
    this.leftBtnText,
    this.rightBtnText,
    this.onCancel,
    this.onConfirm,
    this.customHeaders,
    this.pickerTitleConfig = KqPickerTitleConfig.Default,
    this.showBottomButton = true,
    this.canPop = true,
  }) : super(key: key);

  @override
  KqLinkagePickerBottomSheetState createState() =>
      KqLinkagePickerBottomSheetState();
}

class KqLinkagePickerBottomSheetState
    extends State<KqLinkagePickerBottomSheet> {
  List<int> selectIndex = [];

  List<List<dynamic>> data = [];

  List<FixedExtentScrollController> controllerList = [];

  @override
  void initState() {
    super.initState();
    for (int i = 0; i < widget.totalLevel; i++) {
      selectIndex.add(widget.initSelect != null ? widget.initSelect![i] : 0);
      controllerList
          .add(FixedExtentScrollController(initialItem: selectIndex[i]));
      if (i == 0) {
        data.add(widget.onFillData(0, null, null, null));
      } else {
        data.add(widget.onFillData(i, data[i - 1], selectIndex[i - 1],
            data[i - 1][selectIndex[i - 1]]));
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return UnconstrainedBox(
        child: SizedBox(
            width: context.width,
            child: Material(
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(KqThemeManager.instance
                                .getConfig()
                                .dialogConfig
                                .radius ??
                            8.r),
                        topRight: Radius.circular(KqThemeManager.instance
                                .getConfig()
                                .dialogConfig
                                .radius ??
                            8.r))),
                color:
                    KqThemeManager.instance.getConfig().dialogConfig.bgColor ??
                        KqThemeColors.bgWhite,
                child: ClipRRect(
                  borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(KqThemeManager.instance
                              .getConfig()
                              .dialogConfig
                              .radius ??
                          8.r),
                      topRight: Radius.circular(KqThemeManager.instance
                              .getConfig()
                              .dialogConfig
                              .radius ??
                          8.r)),
                  child: _pickerWidget(context),
                ))));
  }

  Widget _pickerWidget(BuildContext context) {
    return GestureDetector(
      child: Material(
          color: Colors.transparent, child: _renderPickerView(context)),
    );
  }

  Widget _renderPickerView(BuildContext context) {
    if (widget.pickerTitleConfig.titleContent != null ||
        widget.pickerTitleConfig.showTitle) {
      return Column(mainAxisSize: MainAxisSize.min, children: <Widget>[
        if (widget.pickerTitleConfig.titleContent != null) _buildTitleWidget(),
        ...(widget.customHeaders ?? []),
        _linkagePickerBody(),
        ..._buildBottomButton()
      ]);
    }
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [_linkagePickerBody(), ..._buildBottomButton()],
    );
  }

  /// 标题控件
  _buildTitleWidget() {
    return Column(
      children: [
        Padding(
          padding:
              EdgeInsets.only(left: 15.r, right: 15.r, top: 10.r, bottom: 10.r),
          child: Row(
            children: [
              Visibility(
                  visible: !widget.showBottomButton,
                  child: KqInkWell(
                    radius: 4.r,
                    horizontalPadding: 8.r,
                    verticalPadding: 6.r,
                    child: Text(
                      widget.leftBtnText ?? KqIntl.currentResource.cancel,
                      style: TextStyle(
                          fontSize: 16.sp, color: KqThemeColors.text222),
                    ),
                    onTap: () => _onPressedCancel(),
                  )),
              Expanded(
                  child: Text(
                widget.pickerTitleConfig.titleContent!,
                textAlign: TextAlign.center,
                style: TextStyle(
                    fontSize: 16.sp,
                    color: KqThemeColors.text222,
                    fontWeight: FontWeight.w600),
              )),
              Visibility(
                  visible: !widget.showBottomButton,
                  child: KqInkWell(
                    radius: 4.r,
                    horizontalPadding: 8.r,
                    verticalPadding: 6.r,
                    child: Text(
                      widget.rightBtnText ?? KqIntl.currentResource.confirm,
                      style: TextStyle(
                          fontSize: 16.sp,
                          color:
                              KqThemeManager.getCommonConfig().mainLightColor),
                    ),
                    onTap: () => _onPressedConfirm(),
                  )),
            ],
          ),
        ),
        Visibility(visible: !widget.showBottomButton, child: const KqDivider())
      ],
    );
  }

  /// 底部2个按钮
  _buildBottomButton() {
    if (!widget.showBottomButton) {
      return [
        SizedBox(
          width: 1,
          height: KqScreenUtil().bottomBarHeight,
        )
      ];
    }
    return [
      SizedBox(
        width: 1.r,
        height: 10.r,
      ),
      const KqDivider(),
      Row(
        children: [
          Expanded(
              child: KqInkWell(
            onTap: () => _onPressedCancel(),
            child: Container(
              alignment: Alignment.center,
              width: double.infinity,
              height: 48.r,
              child: Text(
                widget.leftBtnText ?? KqIntl.currentResource.cancel,
                style: TextStyle(fontSize: 16.sp, color: KqThemeColors.text8C),
              ),
            ),
          )),
          KqVerticalDivider(
            height: 48.r,
          ),
          Expanded(
              child: KqInkWell(
            onTap: () => _onPressedConfirm(),
            child: Container(
              alignment: Alignment.center,
              width: double.infinity,
              height: 48.r,
              child: Text(
                widget.rightBtnText ?? KqIntl.currentResource.confirm,
                style: TextStyle(
                    fontSize: 16.sp,
                    color: KqThemeManager.getCommonConfig().mainLightColor ??
                        KqThemeColors.textLightBlue),
              ),
            ),
          ))
        ],
      )
    ];
  }

  /// 取消
  void _onPressedCancel() {
    if (widget.onCancel != null) {
      widget.onCancel!();
    }
    Navigator.pop(context);
  }

  /// 确定
  void _onPressedConfirm() {
    if (widget.onConfirm != null) {
      List<dynamic> list = [];
      for (int i = 0; i < data.length; i++) {
        list.add(data[i][selectIndex[i]]);
      }
      bool close = widget.onConfirm!(selectIndex, list);
      if (close) {
        if (widget.canPop) Navigator.pop(context);
      }
    } else {
      if (widget.canPop) Navigator.pop(context);
    }
  }

  /// 多级联动体
  Widget _linkagePickerBody() {
    List<Widget> pickers = [];
    for (int i = 0; i < widget.totalLevel; i++) {
      pickers.add(_singlePickerBody(i));
    }
    return Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween, children: pickers);
  }

  /// 单级滚动体
  Widget _singlePickerBody(int level) {
    return Expanded(
      flex: 1,
      child: Container(
        height: widget.showBottomButton ? 200.r : 260.r,
        decoration: const BoxDecoration(color: KqThemeColors.bgWhite),
        child: KqPicker.builder(
          backgroundColor: KqThemeColors.bgWhite,
          lineColor: KqThemeColors.bgF0,
          scrollController: controllerList[level],
          diameterRatio: widget.showBottomButton ? 1.4 : 3.0,
          itemExtent: 48.r,
          onSelectedItemChanged: (index) {
            setState(() {
              selectIndex[level] = index;
              for (int i = level + 1; i < widget.totalLevel; i++) {
                selectIndex[i] = 0;
                data[i] = widget.onFillData(i, data[i - 1], selectIndex[i - 1],
                    data[i - 1][selectIndex[i - 1]]);
                controllerList[i] = FixedExtentScrollController();
              }
            });
          },
          childCount: data[level].length,
          itemBuilder: (context, index) =>
              _pickerItem(level, data[level][index]),
        ),
      ),
    );
  }

  /// 选中项
  Widget _pickerItem(int level, dynamic item) {
    TextStyle textStyle = TextStyle(
        fontSize: widget.showBottomButton ? 14.sp : 16.sp,
        color: KqThemeColors.text26);
    return Container(
      height: 48.r,
      alignment: Alignment.center,
      child: Text(widget.showWhatInItem(level, item) ?? '', style: textStyle),
    );
  }
}
